package com.ijava.base.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ijava.base.dao.DictionaryDetailDAO;
import com.ijava.base.domain.DictionaryDefine;
import com.ijava.base.domain.DictionaryDetail;
import com.ijava.base.domain.User;
import com.ijava.base.service.DictionaryDetailService;

public class DictionaryDetailServiceImpl implements DictionaryDetailService {
	private static final Logger logger = LoggerFactory.getLogger(DictionaryDetailServiceImpl.class);
	private DictionaryDetailDAO dao;

	// private DataSource dataSource;

	// public DataSource getDataSource() {
	// return dataSource;
	// }
	//
	// public void setDataSource(DataSource dataSource) {
	// this.dataSource = dataSource;
	// }

	public DictionaryDetailDAO getDao() {
		return dao;
	}

	public void setDao(DictionaryDetailDAO dao) {
		this.dao = dao;
	}

	public void remove(String id) throws Exception {
		dao.remove(id);
	}

	public void removeProcess(DictionaryDetail dictionaryDetail) throws Exception {
		try {
			String pid = get(dictionaryDetail.getDetailId()).getDetailParentId();
			remove(dictionaryDetail.getDetailId());
			DictionaryDetail parent = get(pid);
			if(null != parent){
				List list = find(parent);
				if(list.size() == 0){
					parent.setDetailIsLeaf(1);
					update(parent);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public void mutilRemove(DictionaryDetail dictionaryDetail) throws Exception {
		try {
			String[] keys = dictionaryDetail.getKeys();
			if(null == keys)
				return;
			for (int i = 0; i < keys.length; i++) {
				remove(keys[i]);
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public void save(DictionaryDetail dictionaryDetail)
			throws Exception {
		dao.save(dictionaryDetail);
	}

	public void saveAll(DictionaryDetail dictionaryDetail, User user)
			throws Exception {
		try {

			List dictionaryDetails = new ArrayList();
			String[] detailIds = dictionaryDetail.getDetailIds();
			String[] detailCodes = dictionaryDetail.getDetailCodes();
			String[] detailNames = dictionaryDetail.getDetailNames();
			String[] detailExplains = dictionaryDetail.getDetailExplains();
			int[] rowOrders = dictionaryDetail.getRowOrders();
			int[] detailIsLeafs = dictionaryDetail.getDetailIsLeafs();
			
			for (int i = 0; i < detailIds.length; i++) {
				DictionaryDetail e = new DictionaryDetail();
				if ("_".equals(detailIds[i])) {
					e.setDetailId(null);
					e.setCrTime(new Date(System.currentTimeMillis()));
					e.setCrUserId(user.getUserId());
					e.setDetailIsLeaf(1);
				} else {
					e.setDetailIsLeaf(detailIsLeafs[i]);
					e.setDetailId(detailIds[i]);
					e.setUpTime(new Date(System.currentTimeMillis()));
					e.setUpUserId(user.getUserId());
				}
				e.setDetailLevel(dictionaryDetail.getDetailLevel() + 1);
				e.setDetailParentId(dictionaryDetail.getDetailId());
				e.setRowEnable(1);
				e.setDetailCode(detailCodes[i]);
				e.setDetailName(detailNames[i]);
				e.setDetailExplain(detailExplains[i]);
				e.setRowOrder(rowOrders[i]);

				dictionaryDetails.add(e);
			}

			for (int i = 0; i < dictionaryDetails.size(); i++) {
				DictionaryDetail detail = (DictionaryDetail) dictionaryDetails
						.get(i);
				dao.saveOrUpdate(detail);
			}

			dictionaryDetail = dao.get(dictionaryDetail.getDetailId());
			if (null != dictionaryDetail) {
				dictionaryDetail.setDetailIsLeaf(0);
				dao.update(dictionaryDetail);
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public void update(DictionaryDetail dictionaryDetail) throws Exception {
		dao.update(dictionaryDetail);
	}

	public void saveOrUpdate(DictionaryDetail dictionaryDetail)
			throws Exception {
		dao.saveOrUpdate(dictionaryDetail);
	}

	public DictionaryDetail get(String id) throws Exception {
		return dao.get(id);
	}

	public List find(DictionaryDetail dictionaryDetail) throws Exception {
		try {
			List paramList = new ArrayList();
			StringBuffer condition = new StringBuffer();

			condition.append(" where detailParentId = ?");
			paramList.add(dictionaryDetail.getDetailId());

			String queryString = "from " + DictionaryDetail.class.getName()
					+ condition.toString();
			return dao.find(queryString, paramList);
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public List findWithPaging(DictionaryDetail dictionaryDetail)
			throws Exception {
		try {
			int firstRow = (dictionaryDetail.getPageNo() - 1)
					* dictionaryDetail.getPageSize();
			int maxRow = dictionaryDetail.getPageSize();

			// JdbcTemplate template = new JdbcTemplate(dataSource);
			// int total =
			// template.queryForInt("SELECT COUNT(1) FROM TABLE_NAME");
			// dictionaryDetail.setTotal(total);

			List paramList = new ArrayList();
			StringBuffer condition = new StringBuffer();
			if (StringUtils.hasLength(dictionaryDetail.getDetailId())) {
				condition.append(" where detailParentId = ?");
				paramList.add(dictionaryDetail.getDetailId());

				List list = dao.find(
						"select count(*) from "
								+ DictionaryDetail.class.getName()
								+ condition.toString(), paramList);
				dictionaryDetail.setTotal(Integer.parseInt(list.get(0)
						.toString()));

				String queryString = "from " + DictionaryDetail.class.getName()
						+ condition.toString();
				return dao.findWithPaging(queryString, paramList, firstRow, maxRow);
			} else {
				return new ArrayList();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public List findTree(String detailId, List list) throws Exception {
		try {
			List paramList = new ArrayList();
			paramList.add(detailId);

			List childList = dao.find(
					"from " + DictionaryDetail.class.getName()
							+ " where detailParentId = ?", paramList);
			for (int i = 0; i < childList.size(); i++) {
				DictionaryDetail e = (DictionaryDetail) childList.get(i);
				list.add(e);
				if (e.getDetailIsLeaf() == 0) {
					findTree(e.getDetailId(), list);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
		return list;
	}
	
	
	public List findChild(DictionaryDefine dictionaryDefine) throws Exception {
		try {
			List paramList = new ArrayList();
			String[] keys = dictionaryDefine.getKeys();
			String sql = "from " + DictionaryDetail.class.getName()+" where detailParentId = ?";
			if(null != keys && keys.length > 0){
				StringBuffer condition = new StringBuffer("from " + DictionaryDetail.class.getName()+" where detailParentId in (");
				for (int i = 0; i < keys.length; i++) {
					paramList.add(keys[i]);
					condition.append("?");
					if(i != (keys.length -1)){
						condition.append(",");
					}
				}
				condition.append(")");
				sql = condition.toString();
			}else{
				paramList.add(dictionaryDefine.getDefineId());
			}
			return dao.find(sql, paramList);	
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

}
